package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.member;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.data.dto.AjaxResult;
import com.gzhryc.common.data.dto.ListResult;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.kafka.JFKafkaProducer;
import com.gzhryc.common.kafka.KafkaProducerFactory;
import com.gzhryc.common.kafka.models.KafkaMessage;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.DateBranchHelper;
import com.gzhryc.servlet.DtoConstants;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.oem.code.member.dao.enums.MemberBusinessOrderEnum;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrder;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrderUser;
import com.gzhryc.shared_device.oem.code.profit.dao.enums.BusinessOrderEnum;
import com.gzhryc.shared_device.oem.code.profit.event.UserProfitCancelEvent;
import com.gzhryc.shared_device.oem.code.profit.event.UserProfitDivideEvent;
import com.gzhryc.shared_device.oem.code.profit.service.BusinessOrderService;
import com.gzhryc.shared_device.oem.code.profit.service.BusinessOrderUserService;
import com.gzhryc.shared_device.oem.code.KafkaEventConstants;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberBusinessOrder;
import com.gzhryc.shared_device.oem.code.member.services.MemberBusinessOrderService;
import com.gzhryc.shared_device.oem.code.member.services.dto.MemberBusinessOrderSearch;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrderUserProfit;
import com.gzhryc.shared_device.oem.code.profit.service.BusinessOrderUserProfitService;
import com.gzhryc.shared_device.oem.code.user.dao.db.User;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;
import org.apache.commons.lang3.time.DateFormatUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 会员业务订单页面控制器
 * @version 2022-11-03
 */
public class MemberBusinessOrderController {

    static Logger log = Logger.getLogger(MemberBusinessOrderController.class);

    @Route(value = { "/member/order/list.html" })
    public String list(HttpServletRequest request) {
        request.setAttribute("dateBranchItemList", DateBranchHelper.self().getYearDateBranchItems());
        request.setAttribute("businessTypeList",EBusinessType.values());
        request.setAttribute("stateList",MemberBusinessOrderEnum.State.values());
        request.setAttribute("divideStateList",BusinessOrderEnum.DivideState.values());
        return "/member/order/list.html";
    }

    @Route(value = "/member/order/list.data")
    public ListResult<MemberBusinessOrder> listData(HttpServletRequest request) {
        ListResult<MemberBusinessOrder> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        MemberBusinessOrderSearch search = WebUtils.getParameter(request, MemberBusinessOrderSearch.class);
        Integer pageNo = WebUtils.getInteger(request, "page", 1);
        Integer pageLimit = WebUtils.getInteger(request, "limit", WebConstants.PAGE_LIMIT);
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (loginUser != null) {
            search.setAgentId(loginUser.getId());
            Date dateBranch = new Date();
            if(StringTools.isNotBlank(search.getDateBranchId())){
                dateBranch = DateBranchHelper.getDateByItemId(search.getDateBranchId());
            }
            result.getBody().setTotal(MemberBusinessOrderService.self(dateBranch).countJoinBySearch(search));
            List<MemberBusinessOrder> orderList = MemberBusinessOrderService.self(dateBranch).findJoinBySearch(search, pageNo, pageLimit);
            if (orderList != null && orderList.size() > 0) {
                result.setCode(DtoConstants.SUCCESS, null);
                result.getBody().setData(orderList);
            }
        }
        return result;
    }

    @Route(value = { "/member/order/info.html" })
    public String info(HttpServletRequest request) {
        Date createDate = WebUtils.getDate(request,"createDate");
        String tradeNo = WebUtils.getString(request,"tradeNo");
        if (StringTools.isNotBlank(tradeNo)) {
            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if(loginUser != null) {
                if(createDate == null){
                    createDate = new Date();
                }
                MemberBusinessOrder businessOrder = MemberBusinessOrderService.self(createDate).getByTradeNo(tradeNo);
                if (businessOrder != null && businessOrder.getAgentId() != null && businessOrder.getAgentId().equals(loginUser.getId())) {
                    WebUtils.setAttribute(request, businessOrder);
                }
            }
        }
        return "/member/order/info.html";
    }

    @Route(value = "/member/order/user/list.data")
    public ListResult<BusinessOrderUser> userListData(HttpServletRequest request) {
        ListResult<BusinessOrderUser> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        String tradeNo = WebUtils.getString(request, "tradeNo");
        if (StringTools.isNotBlank(tradeNo)) {
            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if(loginUser != null) {
                Date createDate = WebUtils.getDate(request,"createDate");
                if(createDate == null){
                    createDate = new Date();
                }

                MemberBusinessOrder businessOrder = MemberBusinessOrderService.self(createDate).getByTradeNo(tradeNo);
                if (businessOrder != null && businessOrder.getAgentId() != null && businessOrder.getAgentId().equals(loginUser.getId())) {
                    List<BusinessOrderUser> businessOrderList = BusinessOrderUserService.self(createDate).findJoinByTradeNo(tradeNo);
                    if (businessOrderList != null && businessOrderList.size() > 0) {
                        boolean flag = false;
                        for (BusinessOrderUser orderUser : businessOrderList) {
                            if (orderUser.getUserId().equals(loginUser.getId())) {
                                flag = true;
                                break;
                            }
                        }

                        if (flag) {
                            result.setCode(DtoConstants.SUCCESS, null);
                            result.getBody().setData(businessOrderList);
                        }
                    }
                }
            }else {
                result.setMsg("无权限操作");
            }
        }
        return result;
    }

    @Route(value = { "/member/order/user/refresh.do" })
    public AjaxResult doMemberRefresh(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "刷新失败");
        String tradeNo = WebUtils.getString(request, "tradeNo");
        if (StringTools.isNotBlank(tradeNo)) {
            User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
            if(loginUser != null) {
                Date createDate = WebUtils.getDate(request,"createDate");
                if(createDate == null){
                    createDate = new Date();
                }
                MemberBusinessOrder businessOrder = MemberBusinessOrderService.self(createDate).getByTradeNo(tradeNo);
                if (businessOrder != null && businessOrder.getAgentId() != null && businessOrder.getAgentId().equals(loginUser.getId())) {
                    try {
                        if (BusinessOrderUserService.self(businessOrder.getCreateDate()).refresh(tradeNo)) {
                            result.setCode(DtoConstants.SUCCESS, null);
                        }
                    } catch (LogicException e) {
                        result.setMsg(e.getMessage());
                    }
                }else {
                    result.setMsg("无权限操作");
                }
            }else {
                result.setMsg("无权限操作");
            }
        }
        return result;
    }

    @Route(value = { "/member/order/operate.html" })
    public String operate(HttpServletRequest request, HttpServletResponse response) {
        String tradeNo = WebUtils.getString(request,"tradeNo");
        Date createDate = WebUtils.getDate(request,"createDate");
        if(createDate == null){
            createDate = new Date();
        }
        MemberBusinessOrder businessOrder = MemberBusinessOrderService.self(createDate).getByTradeNo(tradeNo);
        if(businessOrder != null) {
            String createDateStr = DateFormatUtils.format(businessOrder.getCreateDate(),"yyyy-MM-dd HH:mm:ss");
            if(EBusinessType.CDCZ.index().equals(businessOrder.getBusinessType())) {
                WebUtils.sendRedirect(request, response, "/cdcz/order/operate.html?tradeNo="+tradeNo+"&createDate="+createDateStr);
            }else if(EBusinessType.CDB.index().equals(businessOrder.getBusinessType())) {
                WebUtils.sendRedirect(request, response, "/cdb/order/info.html?tradeNo="+tradeNo+"&createDate="+createDateStr);
            }else if(EBusinessType.BXSCN_SHOP.index().equals(businessOrder.getBusinessType())) {
                WebUtils.sendRedirect(request, response, "/bxscn/shop_order/info.html?tradeNo=" + tradeNo+"&createDate="+createDateStr);
            }
        }
        return null;
    }

    @Route(value = { "/member/order/profit.html" })
    public String profitInfo(HttpServletRequest request) {
        String tradeNo = WebUtils.getString(request, "tradeNo");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (StringTools.isNotBlank(tradeNo) && loginUser != null) {
            Date createDate = WebUtils.getDate(request,"createDate");
            if(createDate == null){
                createDate = new Date();
            }

            BusinessOrder businessOrder = BusinessOrderService.self(createDate).getByTradeNo(tradeNo);
            if (businessOrder != null) {
                PlacePhysicalStore leasPhysicalStore = PlacePhysicalStoreService.self().getById(businessOrder.getPlaceId());
                if (leasPhysicalStore != null && leasPhysicalStore.getUserId().equals(loginUser.getId())) {
                    WebUtils.setAttribute(request, businessOrder);
                }
            } else {
                MemberBusinessOrder memberBusinessOrder = MemberBusinessOrderService.self(createDate).getByTradeNo(tradeNo);
                if (memberBusinessOrder != null && memberBusinessOrder.getAgentId() != null && memberBusinessOrder.getAgentId().equals(loginUser.getId())) {
                    WebUtils.setAttribute(request, memberBusinessOrder);
                    request.setAttribute("divideStateName", BusinessOrderEnum.DivideState.Wait.note());
                    request.setAttribute("incomeMoneyStr", "--");
                }
            }
        }
        return "/member/order/profit.html";
    }

    @Route(value = { "/member/order/profit/divide.do" })
    public AjaxResult profitDivide(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "分成失败");
        String tradeNo = WebUtils.getString(request, "tradeNo");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (StringTools.isNotBlank(tradeNo) && loginUser != null) {
            Date createDate = WebUtils.getDate(request, "createDate");
            if (createDate == null) {
                createDate = new Date();
            }

            MemberBusinessOrder memberBusinessOrder = MemberBusinessOrderService.self(createDate).getByTradeNo(tradeNo);
            if (memberBusinessOrder != null && memberBusinessOrder.getAgentId() != null && memberBusinessOrder.getAgentId().equals(loginUser.getId())) {
                Long total = BusinessOrderUserProfitService.self(memberBusinessOrder.getCreateDate()).countByTradeNo(tradeNo);
                if (total != null && total > 0) {
                    result.setMsg("已分成，请先回滚分成后重新分成");
                } else {
                    if (MemberBusinessOrderEnum.State.Finish.index().equals(memberBusinessOrder.getState())) {
                        JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                        if (producer != null) {
                            OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                            operateInfo.setOperator(EOperatorType.Agent.index(), loginUser.getFullName());
                            operateInfo.setOperateNote("后台代理重新分成");

                            //触发分成
                            UserProfitDivideEvent profitDivideEvent = new UserProfitDivideEvent(memberBusinessOrder.getTradeNo(), memberBusinessOrder.getCreateDate(), operateInfo);
                            KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order, KafkaEventConstants.KEY_ProfitDivide, JsonTools.toJson(profitDivideEvent));
                            if (producer.send(kafkaMessage)) {
                                //等待3秒后返回
                                try {
                                    Thread.sleep(3000L);
                                } catch (InterruptedException e) {
                                    //throw new RuntimeException(e);
                                }
                                result.setCode(DtoConstants.SUCCESS, null);
                            }
                        } else {
                            result.setMsg("消息队列未初始化");
                        }
                    } else {
                        result.setMsg("订单未完成，不允许分成");
                    }
                }
            } else {
                result.setMsg("未找到会员业务订单");
                return result;
            }
        }
        return result;
    }

    @Route(value = { "/member/order/profit/revoke.do" })
    public AjaxResult profitRevoke(HttpServletRequest request) {
        AjaxResult result = new AjaxResult(DtoConstants.EXECUTE_ERROR, "回滚分成失败");
        String tradeNo = WebUtils.getString(request, "tradeNo");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (StringTools.isNotBlank(tradeNo) && loginUser != null) {
            Date createDate = WebUtils.getDate(request,"createDate");
            if(createDate == null){
                createDate = new Date();
            }

            BusinessOrder businessOrder = BusinessOrderService.self(createDate).getByTradeNo(tradeNo);
            if (businessOrder != null) {
                PlacePhysicalStore leasPhysicalStore = PlacePhysicalStoreService.self().getById(businessOrder.getPlaceId());
                if (leasPhysicalStore != null && leasPhysicalStore.getUserId().equals(loginUser.getId())) {
                    if (!BusinessOrderEnum.DivideState.Finish.index().equals(businessOrder.getDivideState())) {
                        result.setMsg("订单未分成或未分成成功，无法回滚");
                        return result;
                    }
                    JFKafkaProducer producer = KafkaProducerFactory.self().getProducer();
                    if (producer != null) {
                        OperateInfo operateInfo = new OperateInfo(WebConstants.PROGRAM_TYPE, WebConstants.PROGRAM_TYPE_NAME);
                        operateInfo.setOperator(EOperatorType.Agent.index(), loginUser.getFullName());
                        operateInfo.setOperateNote("后台代理回滚分成");

                        UserProfitCancelEvent profitCancelEvent = new UserProfitCancelEvent(businessOrder.getTradeNo(), businessOrder.getCreateDate(), operateInfo);
                        KafkaMessage kafkaMessage = new KafkaMessage(KafkaEventConstants.TOPIC_Order, KafkaEventConstants.KEY_ProfitCancel, JsonTools.toJson(profitCancelEvent));
                        if (producer.send(kafkaMessage)) {
                            //等待3秒后返回
                            try {
                                Thread.sleep(3000L);
                            } catch (InterruptedException e) {
                                //throw new RuntimeException(e);
                            }
                            result.setCode(DtoConstants.SUCCESS, null);
                        }
                    } else {
                        result.setMsg("消息队列未初始化");
                    }
                }else{
                    result.setCode(DtoConstants.NOT_POWER,"无权限操作");
                }
            }
        }
        return result;
    }

    @Route(value = "/member/order/profit/user/list.data")
    public ListResult<BusinessOrderUserProfit> userProfitListData(HttpServletRequest request) {
        ListResult<BusinessOrderUserProfit> result = new ListResult<>(DtoConstants.NULL_DATA, "暂无数据");
        String tradeNo = WebUtils.getString(request, "tradeNo");
        User loginUser = WebUtils.getAttribute(request, WebConstants.LOGIN_USER, User.class);
        if (StringTools.isNotBlank(tradeNo) && loginUser != null) {
            Date createDate = WebUtils.getDate(request,"createDate");
            if(createDate == null){
                createDate = new Date();
            }
            BusinessOrder businessOrder = BusinessOrderService.self(createDate).getByTradeNo(tradeNo);
            if (businessOrder != null) {
                PlacePhysicalStore leasPhysicalStore = PlacePhysicalStoreService.self().getById(businessOrder.getPlaceId());
                if (leasPhysicalStore != null && leasPhysicalStore.getUserId().equals(loginUser.getId())) {
                    List<BusinessOrderUserProfit> userProfitList = BusinessOrderUserProfitService.self(businessOrder.getCreateDate()).findDivideByTradeNo(tradeNo);
                    if (userProfitList != null && userProfitList.size() > 0) {
                        result.setCode(DtoConstants.SUCCESS, null);
                        result.getBody().setData(userProfitList);
                    }
                }else{
                    result.setCode(DtoConstants.NOT_POWER,"无权限查看");
                }
            }
        }
        return result;
    }
}
